import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_house_manager/constants/index.dart';
import 'package:flutter_house_manager/controller/build_controller.dart';
import 'package:flutter_house_manager/utils/toast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  // 存储位置信息
  String _currentAddress = "";
  List _aroundList = [];
  bool _isLoading = false;

  /// 引入楼栋控制器
  BuildController buildController = Get.find<BuildController>();

  /// 获取定位权限
  getAccess() async {
    PermissionStatus status = await Permission.location.request();
    if (status.isGranted) {
      // 定位权限已获取, 可以开始定位了
      PromptAction.showSuccess('定位权限已获取');
      getLocation();
    } else {
      // 获取定位权限失败, 提示用户去设置打开定位权限
      PromptAction.showWarning('请去设置打开定位权限');
    }
  }

  /// 获取当前位置的经纬度
  getLocation() async {
    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      // 定位权限已拒绝, 提示用户去设置打开定位权限
      PromptAction.showWarning('请去设置打开定位权限');
      return;
    }
    Position position = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high,
    );
    // 打印当前位置的经纬度
    // PromptAction.showSuccess( '当前位置的经纬度: ${position.latitude}, ${position.longitude}');
    // 获取当前位置的详细地址
    getLocationString(position.latitude, position.longitude);
    // 获取附近社区
    getNearList(position.latitude, position.longitude);
  }

  /// 获取当前位置的详细地址
  getLocationString(double latitude, double longitude) async {
    // 1. 创建Dio实例
    Dio dio = Dio();
    // 2. 发起get请求
    final res = await dio.get(
      GlobalVariable.GAO_BASE_URL + HTTP_PATH.REGEO,
      queryParameters: {
        "key": GlobalVariable.GAO_KEY,
        "location": "$longitude,$latitude",
      },
    );
    // 3. 解析数据
    if (res.data['status'] == '1') {
      // 获取成功
      // 获取详细地址
      String address = res.data['regeocode']['formatted_address'];
      // 打印详细地址
      // PromptAction.showSuccess('当前位置的详细地址: $address');
      // 存储位置信息
      setState(() {
        _currentAddress = address;
      });
    } else {
      // 获取失败
      PromptAction.showError('获取详细地址失败');
    }
  }

  /// 获取附近社区
  void getNearList(double latitude, double longitude) async {
    _isLoading = true;
    // 1. 创建Dio实例
    Dio dio = Dio();
    // 2. 发起get请求
    final res = await dio.get(
      GlobalVariable.GAO_BASE_URL + HTTP_PATH.NEARLIST,
      queryParameters: {
        "key": GlobalVariable.GAO_KEY,
        "location": "$longitude,$latitude",
        "keywords": '住宅小区公寓',
        "radius": 2000, // 米
        "offset": 10 // 限制查询的条数
      },
    );
    // 3. 解析数据
    if (res.data['status'] == '1') {
      setState(() {
        _isLoading = false;
        _aroundList = res.data['pois'];
      });
    } else {
      // 获取失败
      PromptAction.showError('获取附近社区失败');
    }
  }

  // --------------------------------
  @override
  void initState() {
    super.initState();
    // getAccess(); //  申请获取地理定位的权限
    getLocationString(40.060294, 116.343367);
    getNearList(40.060294, 116.343367);
  }
  // --------------------------------

  @override
  Widget build(BuildContext context) {
    // 1. 加载中
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          const Row(
            children: [
              Text(
                '当前地址',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(child: Text(_currentAddress)),
                GestureDetector(
                    onTap: () {
                      getLocationString(31.23301, 121.501529);
                      getNearList(31.23301, 121.501529);
                    },
                    child: const Row(
                      children: [
                        Icon(Icons.location_searching_outlined,
                            color: Colors.blue),
                        SizedBox(width: 2),
                        Text(
                          '重新定位',
                          style: TextStyle(color: Colors.blue),
                        ),
                      ],
                    ))
              ],
            ),
          ),
          const SizedBox(height: 10),
          const Row(
            children: [
              Text(
                '附近社区',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: _aroundList.map((item) {
              return Container(
                  color: Colors.white,
                  padding: const EdgeInsets.all(10),
                  child: GestureDetector(
                    onTap: () {
                      // 1. 更新全局数据
                      buildController.updateBuildInfo({
                        'point': item['name'],
                      });

                      // 2. 跳转到楼栋列表页
                      Navigator.pushNamed(context, '/building_list');
                    },
                    child: Row(
                      children: [
                        Expanded(child: Text(item['name'])),
                        const Row(
                          children: [
                            Icon(Icons.arrow_forward_ios,
                                size: 16, color: Colors.black),
                          ],
                        )
                      ],
                    ),
                  ));
            }).toList(),
          )
        ],
      ),
    );
  }
}
